package cn.bugstack.middleware.dynamic.thread.pool.sdk.alarm;

import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolAlarmEntity;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description 线程池告警服务
 */
public class ThreadPoolAlarmService {

    private final Logger logger = LoggerFactory.getLogger(ThreadPoolAlarmService.class);
    
    private final IAlarmNotifier alarmNotifier;
    
    public ThreadPoolAlarmService(IAlarmNotifier alarmNotifier) {
        this.alarmNotifier = alarmNotifier;
    }
    
    /**
     * 检查线程池状态并发送告警
     * @param threadPoolConfig 线程池配置
     * @param alarmConfig 告警配置
     */
    public void checkAndAlarm(ThreadPoolConfigEntity threadPoolConfig, ThreadPoolAlarmEntity alarmConfig) {
        // 如果未启用告警，直接返回
        if (!alarmConfig.isAlarmEnabled()) {
            return;
        }
        
        // 检查活跃线程数
        if (alarmConfig.getActiveCountThreshold() > 0 && 
                threadPoolConfig.getActiveCount() >= alarmConfig.getActiveCountThreshold()) {
            String alarmMessage = String.format("活跃线程数超过阈值！当前值：%d，阈值：%d", 
                    threadPoolConfig.getActiveCount(), 
                    alarmConfig.getActiveCountThreshold());
            alarmNotifier.notify(threadPoolConfig, alarmConfig, alarmMessage);
        }
        
        // 检查队列使用率
        if (alarmConfig.getQueueCapacityThreshold() > 0) {
            int totalCapacity = threadPoolConfig.getQueueSize() + threadPoolConfig.getRemainingCapacity();
            if (totalCapacity > 0) {
                int usagePercentage = threadPoolConfig.getQueueSize() * 100 / totalCapacity;
                if (usagePercentage >= alarmConfig.getQueueCapacityThreshold()) {
                    String alarmMessage = String.format("队列使用率超过阈值！当前使用率：%d%%，阈值：%d%%", 
                            usagePercentage, 
                            alarmConfig.getQueueCapacityThreshold());
                    alarmNotifier.notify(threadPoolConfig, alarmConfig, alarmMessage);
                }
            }
        }
    }
}